package org.pangu.config;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author zhangyj
 * @date 2021/8/28 16:47
 */
@Configuration
@Slf4j
public class MessageListenerConcurrentlyHandler implements MessageListenerConcurrently {
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        if (CollectionUtil.isEmpty(msgs)) {
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        log.info("消费消息条数[{}]", msgs.size());
        for (MessageExt msg : msgs) {
            try {
                mockConsumer(msg);
            } catch (InterruptedException | UnsupportedEncodingException e) {
                log.error("消费消息msg[{}]，失败[{}]", JSON.toJSONString(msg), e);
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    public void mockConsumer(MessageExt msg) throws InterruptedException, UnsupportedEncodingException {
        Thread.sleep(100);
        String body = new String(msg.getBody(), "utf8");
        log.info("消费消息msg-body[{}]", body);

    }
}
